package com.deck.server.server;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import com.deck.server.shared.domain.Card;
import com.deck.server.shared.domain.Deck;
import com.deck.server.shared.domain.DeckInfo;



/**
 * 
 */

/**
 * @author Vincentas
 *
 */
public class DeckImport {

	/**
	 * @param args
	 * @throws XPathExpressionException 
	 * @throws IOException 
	 * @throws MalformedURLException 
	 * @throws IOException 
	 * @throws MalformedURLException 
	 * @throws ParserConfigurationException 
	 * @throws SAXException 
	 * @throws ParserConfigurationException 
	 * @throws SAXException 
	 */
	@SuppressWarnings("unchecked")
	public static void main(String[] args) throws XPathExpressionException, MalformedURLException, IOException, ParserConfigurationException, SAXException {
		String deckUrl = "http://quizlet.com/1624451";
		
		Pattern pattern = Pattern.compile(".*?(\\d+)");
		Matcher matcher = pattern.matcher(deckUrl);
		String deckId;
		if (matcher.matches()) {
			deckId = matcher.group(1);
		} else {
			return;
		}
				
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
		
		DocumentBuilder documentBuilder = factory.newDocumentBuilder();
		
		XPath xPath = XPathFactory.newInstance().newXPath();
		XPathExpression xPathExpression = xPath.compile("//textarea");
		
		InputStream is = new URL(deckUrl + "/export").openStream();
		
		Document document = documentBuilder.parse(is);
		String result = xPathExpression.evaluate(document);
		
		List<String> readLines = IOUtils.readLines(new StringReader(result));
		
		Deck deck = new Deck();

		Set<Card> cards = new HashSet<Card>();
		
		int id = 0;
		for (String line : readLines) {
			String[] parts = StringUtils.split(line, "\\t");
			
			Card card = new Card();
			card.setFront(parts[1]);
			card.setBack(parts[0]);
			card.setId(Integer.toString(id++));
			
			cards.add(card);
		}
		
		DeckInfo deckInfo = new DeckInfo();
		deckInfo.setId(deckId);
		deckInfo.setCardCount(cards.size());
		deckInfo.setName("");
		deckInfo.setDescription("");
		
		deck.setCards(cards);
		deck.setDeckInfo(deckInfo);
	}

}
